package com.gitee.deament.tianyancha.core;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.gitee.deament.tianyancha.core.base.HttpRequestI;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


import java.util.List;
import java.util.Map;

/**
 * @author deament
 */
public class HttpRequest implements HttpRequestI {
    Logger logger= LoggerFactory.getLogger(this.getClass());
    /**
     * 用户鉴权token
     */
    private String token;


    public HttpRequest(String token) {
        this.token = token;
    }



    /**
     * get 请求
     *
     * @param url    地址
     * @param params 参数
     * @param clazz  反射的类
     * @param <T>
     * @return 反射的类的实例
     * @throws Exception
     */
    public <T> T get(String url, Map<String, Object> params, Class<T> clazz) throws Exception {
        String result = this.get(url, params);
        return JSONObject.parseObject(result, clazz);
    }

    /**
     * get 请求
     *
     * @param url    地址
     * @param params 参数
     * @param clazz  反射的类
     * @param <T>
     * @return 反射的类的实例
     * @throws Exception
     */
    public <T> List<T> getList(String url, Map<String, Object> params, Class<T> clazz) throws Exception {
        String result = this.get(url, params);
        return JSONArray.parseArray(result, clazz);
    }


    public String get(String url, Map<String, Object> params) throws Exception {
        if(params!=null&& params.size()>0){
            url+="?";
            boolean isFirst=true;
            for (String key : params.keySet()) {
                if(params.get(key)!=null){
                    //HttpUtil.encodeUtf8(params.get(key).toString())
                    String value=HttpUtil.encodeUtf8(params.get(key).toString());
                    if(isFirst){
                        url+=key+"="+value ;
                    }else{
                        url+="&"+key+"="+value ;
                    }
                    isFirst=false;


                }

            }
        }

        logger.info(url);
        String result = HttpUtil.createGet(url).header("Authorization", token).execute().body();
        return result;
    }


}
